package main

import (
	"fmt"
	"math/rand"
	"sync"
	"time"
)

/*
	goroutine + channel
		计算int64随机数，个位数的和
*/
var (
	wg   sync.WaitGroup
	once sync.Once
)

func write(jobChan chan<- int64) {
	defer wg.Done()
	rand.Seed(time.Now().Unix())
	for i := 0; i < 100; i++ {
		jobChan <- rand.Int63n(1000000)
	}
	close(jobChan)
}

func cal(jobChan <-chan int64, resultChan chan<- int64) {
	defer wg.Done()
	for {
		if val, ok := <-jobChan; ok {
			var sum int64 = 0
			newVal := string(val)
			for _, v := range newVal {
				sum += int64(v)
			}
			resultChan <- sum
		} else {
			break
		}
	}
	// once.Do(func(){close(resultChan)})
	if len(resultChan) == cap(resultChan) {
		// close(resultChan)
		once.Do(func() { close(resultChan) })
	}
}

func main() {
	ch1 := make(chan int64, 50)
	ch2 := make(chan int64, 100)
	wg.Add(25)
	go write(ch1)

	for i := 0; i < 24; i++ {
		go cal(ch1, ch2)
	}

	wg.Wait()

	for {
		if val, ok := <-ch2; ok {
			fmt.Println(val)
		} else {
			break
		}
	}

}
